<template>
  <a-modal
    title="新建歌单"
    :width="600"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    okText="确认"
    cancelText="取消"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="6">
          <a-col :md="12" :sm="24">
            <a-form-item
              label="歌单名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input
                v-decorator="['playlistName', {rules: [{required: true, message: '请输入歌单名称', trigger: 'blur' }]}]" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="歌单标签"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <span>
                <edit-tag
                  ref="editTag"
                  :tags="tags"
                  :tagIds="tagIds"
                  :prevent="true"
                  @ok="handleTag"
                  v-if="tagVisible"/>
              </span>
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-item
              label="歌单详情"
              :labelCol="{span: 4}"
              :wrapperCol="{span: 20}"
            >
              <a-input
                v-decorator="['playlistInfo']" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-upload
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :before-upload="() => { return false }"
              accept="image/*"
              @change="handleChange"
            >
              <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 100%;height: 100%"/>
              <div v-else>
                <a-icon :type="'plus'" />
                <div class="ant-upload-text">
                  封面
                </div>
              </div>
            </a-upload>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-checkbox :checked="isPublic" @change="onChange">
              是否公开此歌单
            </a-checkbox>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <edit-image ref="editImage" @ok="handleOk"/>
  </a-modal>
</template>

<script>
  import TagSelectOption from '@/components/TagSelect/TagSelectOption'
  import { add } from '@/api/music/playlist'
  import { upload } from '@/api/file/file'
  import EditImage from '@/views/music/modules/playlist/EditImage'
  import EditTag from '@/views/music/modules/playlist/EditTag'
  function getBase64 (img, callback) {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }
  export default {
    components: {
      TagSelectOption,
      EditImage,
      EditTag
    },
    props: {
      tags: {
        type: Array,
        default () {
          return []
        }
      }
    },
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        visible: false,
        tagVisible: true,
        confirmLoading: false,
        form: this.$form.createForm(this),
        file: {},
        imageUrl: '',
        tagIds: '',
        isPublic: true
      }
    },
    methods: {
      add () {
        this.visible = true
      },
      handleTag (tagIds) {
        this.tagIds = tagIds
        this.tagVisible = false
        setTimeout(() => {
          this.tagVisible = true
          setTimeout(() => {
            this.$refs.editTag.init()
          }, 1)
        }, 1)
      },
      onChange () {
        this.isPublic = !this.isPublic
      },
      handleChange (info) {
        if (info.file.type.indexOf('image') === -1) {
          this.$message.warning('请选择图片文件')
          return
        }
        if (info.file.size / 1024 / 1024 > 2) {
          this.$message.warning('请选择不超过2MB大小的图片')
          return
        }
        this.file = info.file
        getBase64(info.file, imageUrl => {
          this.imageUrl = imageUrl
          this.$refs.editImage.edit(imageUrl, info.file.name)
        })
      },
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            if (this.file.type !== undefined) {
              const formData = new FormData()
              formData.append('file', this.file)
              formData.append('type', 'image')
              upload(formData)
                .then(res => {
                  if (res.data.message !== 'error') {
                    values.imageUrl = res.data.result.saveName
                    values.imageName = this.file.name
                    this.submitPlaylist(values)
                  } else {
                    this.$message.error('附件上传失败！')
                  }
                })
            } else {
              values.imageUrl = '周杰伦.jpg'
              values.imageName = '周杰伦.jpg'
              this.submitPlaylist(values)
            }
          } else {
            this.confirmLoading = false
          }
        })
      },
      submitPlaylist (values) {
        if (this.isPublic) {
          values.isPublic = 1
        } else {
          values.isPublic = 0
        }
        values.tagId = this.tagIds
        add(values)
          .then(res => {
            if (res.data.message !== 'error') {
              this.$emit('ok')
              this.reset()
              this.$message.success('操作成功！')
            } else {
              this.confirmLoading = false
              this.$message.error('操作失败！')
            }
          })
      },
      handleCancel () {
        this.reset()
      },
      handleOk (newImageUrl) {
        this.imageUrl = newImageUrl
        this.file = this.toFile(newImageUrl)
      },
      toFile (dataurl) {
        const arr = dataurl.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], this.file.name, { type: mime })
      },
      reset () {
        this.visible = false
        this.confirmLoading = false
        this.form.resetFields()
        this.file = {}
        this.imageUrl = ''
        this.isPublic = true
      }
    }
  }
</script>
